package org.server.service;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author Admin
 */
@Component
public class PokerService {
    private final Integer[] POKER = {
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            , 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
            , 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
            , 31, 32, 33, 34, 35, 36, 37, 38, 39, 40
            , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
            , 51, 52, 53, 54};

    /**
     * 发牌
     *
     * @param
     * @return java.util.List<java.util.List < java.lang.Integer>>
     * @author Tang
     * @date 2023/2/26 10:39
     **/
    public List<List<Integer>> deal() {
        List<Integer> pokers = new ArrayList<>();
        int n = 2;
        for (int i = 0; i < n; i++) {
            Collections.addAll(pokers, POKER);
        }

        iOShuffle(pokers);
        System.out.println(pokers);
        List<List<Integer>> firstDeal = splistList(pokers, 17);
        List<List<Integer>> secondDeal = new ArrayList<>(4);
        for (int i = 0; i < 4; i++) {
            secondDeal.add(firstDeal.get(i));
        }
        return secondDeal;
    }

    //洗牌算法
    private void iOShuffle(List<Integer> pokers) {
        Random rdm = new Random();
        for (int i = pokers.size() - 1; i >= 0; --i) {
            int tempInd = rdm.nextInt(pokers.size());
            Integer temp = pokers.get(i);
            pokers.set(i, pokers.get(tempInd));
            pokers.set(tempInd, temp);
        }

    }

    //排序
    private void pokerSort(List<Integer> pokers) {
        pokers.sort((a, b) -> {
            if (a < 53 && b < 53) {
                if ((a - 1) % 13 == (b - 1) % 13) {
                    return a.compareTo(b);
                }
                Integer aa = (a - 1) % 13;
                Integer bb = (b - 1) % 13;
                return aa.compareTo(bb);
            }
            return a.compareTo(b);
        });
    }

    /**
     * 分割牌堆
     *
     * @param list
     * @param subNum
     * @return java.util.List<java.util.List < T>>
     * @author Tang
     * @date 2023/2/26 10:45
     **/
    private <T> List<List<T>> splistList(List<T> list, int subNum) {
        List<List<T>> tNewList = new ArrayList<List<T>>();
        int priIndex = 0;
        int lastPriIndex = 0;
        int insertTimes = list.size() / subNum;
        List<T> subList;
        for (int i = 0; i <= insertTimes; i++) {
            priIndex = subNum * i;
            lastPriIndex = priIndex + subNum;
            if (i == insertTimes) {
                subList = list.subList(priIndex, list.size());
            } else {
                subList = list.subList(priIndex, lastPriIndex);
            }
            if (subList.size() > 0) {
                tNewList.add(subList);
            }
        }
        return tNewList;
    }
}
